<template>
  <view class="main">
    <u-navbar title="考勤打卡" :autoBack="true"> </u-navbar>
    <view class="btn-group">
      <view class="u-flex u-flex-col u-row-center u-col-center" v-for="(item, index) in tabList" :key="index"
        @click="tabIndex = index">
        <view class="u-font-32 u-m-b-30" :style="{ color: tabIndex == index ? '#C4AD8C' : '#000' }">
          {{ item.name }}
        </view>
        <view v-show="tabIndex == index" style="
            width: 40px;
            height: 5px;
            background-color: #c4ad8c;
            border-radius: 3px;
          ">
        </view>
      </view>
    </view>

    <view class="u-p-t-30 u-p-l-40 u-flex text-black" v-if="tabIndex == 0">
      <!-- <view class="u-m-r-30">第一周</view> -->
      <view>{{ today }}</view>
    </view>

    <view class="collapse" v-if="tabIndex == 0">
      <view class="bg-white u-border-radius">
        <view class="title u-p-lr-30 u-p-t-30">
          <view class="u-font-weight">所属学院：{{ info.cen }}</view>
        </view>


        <view class="u-flex u-row-between u-p-l-30 u-p-tb-20">
          <view class="u-flex">
            <u-icon name="/static/images/user/book.png" width="20" height="20"></u-icon>
            <text class="u-font-weight u-m-l-10">上课考勤</text>
          </view>
          <view class="status u-p-lr-20 u-p-tb-8" :class="upInfo.clockStatus == 1 ?'normal':'error'" v-if="upInfo.id">
            {{ upInfo.clockStatus == 1 ? "正常" : "异常" }}
          </view>
        </view>

        <view class="clock u-p-l-30 u-p-b-30">
          <view class="u-flex u-row-between">
            <view class="clock-item u-flex-1">
              <text class="text-black">课程名称:</text>
              <text class="text-tips u-m-l-10">{{ info.sn }}</text>
            </view>
            <view class="clock-item u-flex-1">
              <text class="text-black">基准打卡:</text>
              <text class="text-tips u-m-l-10">{{ upInfo.standardTime || info.st }}</text>
            </view>
          </view>
          <view class="u-flex u-row-between u-p-tb-20">
            <view class="clock-item u-flex-1">
              <text class="text-black">任课老师:</text>
              <text class="text-tips u-m-l-10">{{ info.tn }}</text>
            </view>
            <view class="clock-item u-flex-1">
              <text class="text-black">打卡地点:</text>
              <text class="text-tips u-m-l-10">{{ info.ad }}</text>
            </view>
          </view>
          <view class="u-flex u-row-between">
            <view class="clock-item u-flex-1">
              <text class="text-black">打卡结果:</text>
              <text class="text-tips u-m-l-10">{{ !upInfo.id?'':upInfo.clockStatus == 1 ? "正常" : "异常" }}</text>
            </view>
            <view class="clock-item u-flex-1">
              <text class="text-black">打卡来源:</text>
              <text class="text-tips u-m-l-10">{{ clockTypeText(upInfo.clockType) }}</text>
            </view>
          </view>
          <view class="u-p-t-20">
            <text class="text-black">打卡时间:</text>
            <text class="text-tips u-m-l-10">{{ upInfo.clockTime }}</text>
            <text class="text-tips u-m-l-30">{{ weekIdText(upInfo.weekId) }}</text>
          </view>
        </view>

        <view class="u-flex u-row-between u-p-l-30 u-p-b-20">
          <view class="u-flex">
            <u-icon name="/static/images/user/book.png" width="20" height="20"></u-icon>
            <text class="u-font-weight u-m-l-10">下课考勤</text>
          </view>
          <view class="status u-p-lr-20 u-p-tb-8" :class="downInfo.clockStatus == 1 ?'normal':'error'"
            v-if="downInfo.id">
            {{ downInfo.clockStatus == 1 ? "正常" : "异常" }}
          </view>
        </view>

        <view class="clock u-p-l-30 u-p-b-30">
          <view class="u-flex u-row-between">
            <view class="clock-item u-flex-1">
              <text class="text-black">课程名称:</text>
              <text class="text-tips u-m-l-10">{{ info.sn }}</text>
            </view>
            <view class="clock-item u-flex-1">
              <text class="text-black">基准打卡:</text>
              <text class="text-tips u-m-l-10">{{ downInfo.standardTime || info.se }}</text>
            </view>
          </view>
          <view class="u-flex u-row-between u-p-tb-20">
            <view class="clock-item u-flex-1">
              <text class="text-black">任课老师:</text>
              <text class="text-tips u-m-l-10">{{ info.tn }}</text>
            </view>
            <view class="clock-item u-flex-1">
              <text class="text-black">打卡地点:</text>
              <text class="text-tips u-m-l-10">{{ info.ad }}</text>
            </view>
          </view>
          <view class="u-flex u-row-between">
            <view class="clock-item u-flex-1">
              <text class="text-black">打卡结果:</text>
              <text class="text-tips u-m-l-10">{{ !downInfo.id?'':downInfo.clockStatus == 1 ? "正常" : "异常" }}</text>
            </view>
            <view class="clock-item u-flex-1">
              <text class="text-black">打卡来源:</text>
              <text class="text-tips u-m-l-10">{{ clockTypeText(downInfo.clockType) }}</text>
            </view>
          </view>
          <view class="u-p-t-20">
            <text class="text-black">打卡时间:</text>
            <text class="text-tips u-m-l-10">{{ downInfo.clockTime }}</text>
            <text class="text-tips u-m-l-30">{{ weekIdText(downInfo.weekId) }}</text>
          </view>
        </view>

      </view>
    </view>

    <!-- 打卡 -->
    <view class="clock-btn" @click="clockIn" v-if="tabIndex == 0">
      <view class="click-btn">
        <view class="u-font-32 u-font-weight">{{userType==3?'打卡二维码':'打卡'}}</view>
        <view class="u-m-t-15">{{ clockTimeNow }}</view>
      </view>
    </view>

    <view class="u-p-b-30" v-if="tabIndex == 1">

      <!-- 查询条件 -->
      <view class="u-flex u-row-between u-col-center bg-white" style="padding:10px;">
        <view style="margin-right: 5px;" @click="showClockTime = true">
          <u-input v-model="clockTimeText" readonly placeholder="选择时间">
            <template slot="suffix">
              <u-icon name="arrow-down"></u-icon>
            </template>
          </u-input>
        </view>
        <view style="margin-right: 5px;" @click="statusShow = true">
          <u-input v-model="clockStatusText" readonly placeholder="选择打卡状态">
            <template slot="suffix">
              <u-icon name="arrow-down"></u-icon>
            </template>
          </u-input>
        </view>

        <view>
          <u-button type="primary"
            customStyle="background:#182044;color:#C4AD8C;border-radius:7px;padding:17px;border:none;" size="small"
            text="重置" @click="reset"></u-button>
          <u-button type="primary"
            customStyle="background:#182044;color:#C4AD8C;border-radius:7px;padding:17px;border:none;margin-top:10rpx"
            size="small" text="查询" @click="refresh"></u-button>
        </view>

      </view>

      <view class="logInfo u-border-radius" v-for="(item, index) in clockList" :key="index">
        <view>课程：<text>{{ item.subjectName }}</text></view>
        <view>打卡时间：<text>{{ item.clockTime }}</text></view>
        <view>打卡地点：<text>{{ item.address }}</text></view>
      </view>
    </view>
    <!--  -->
    <u-picker :show="statusShow" :columns="[clockStatusList]" keyName="label" @confirm="confirmClockStatus"></u-picker>
    <u-calendar :show="showClockTime" monthNum="13" mode="range" :maxDate="maxDate" :minDate="minDate"
      @confirm="confirmClockTime" @close="showClockTime=false"></u-calendar>
  </view>
</template>

<script>
  import {
    mapState,
    mapGetters
  } from "vuex";
  import {
    getStudentClockList,
    getTeacherClockList,
    getTodayClock,
    getTeacherTodayClock,
    createClock,
  } from "@/api/user.js";
  export default {
    data() {
      return {
        clockTimeNow: "",
        isHide: false,
        info: {},
        upInfo: {},
        downInfo: {},
        openList: ["clock"],
        tabIndex: 0,
        tabList: [{
            name: "今日考勤",
          },
          {
            name: "考勤记录",
          },
        ],
        btnType1: "primary",
        btnType2: "",
        query: {
          pageNo: 1,
          pageSize: 10,
          'clockTime%5B0%5D': '',
          'clockTime%5B1%5D': '',
          clockStatus: ''
        },
        isLast: false,
        clockList: [],
        todayList: [],
        clockTypes: [],
        statusShow: false,
        showClockTime: false,
        clockStatusList: [],
        clockStatusText: '',
        clockTimeText: ''
      };
    },
    computed: {
      ...mapState(["userInfo", "userType", "userId", 'dictDataList']),
      today() {
        return this.$u.timeFormat(+new Date(), "yyyy-mm-dd");
      },
      formatDate() {
        return this.$u.timeFormat(+new Date(), "yyyy-mm-dd") + " 00:00:00";
      },
      clockTypeText() {
        return value => {
          let row = this.clockTypes.find(item => item.value == value);
          return row ? row.label : '';
        }
      },
      weekIdText() {
        return value => {
          let weeks = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
          return weeks[value - 1] ? weeks[value - 1] : '';
        }
      },
      minDate() {
        return +new Date() - 31536000000
      },
      maxDate() {
        return +new Date() + 1000;
      }
    },
    watch: {
      tabIndex(val) {
        if (val == 0) {
          this.getTodayClock();
        } else {
          this.refresh();
        }
      },
    },
    onLoad(e) {
      this.info = e;
      this.stId = e.stId;
      this.setClockTimeNow();
      this.clockTypes = this.dictDataList.filter(item => item.dictType === 'class_clock_type');
      this.clockStatusList = this.dictDataList.filter(item => item.dictType === 'accommodation_clock_status');
    },
    onShow() {
      if (this.isHide) {
        this.isHide = false;
        this.setClockTimeNow();
      }
      this.getTodayClock();
    },
    onHide() {
      this.isHide = true;
    },
    onUnload() {
      this.isHide = true;
    },
    onReachBottom() {
      // this.loadMore()
    },
    methods: {
      setClockTimeNow() {
        this.clockTimeNow = this.$u.timeFormat(+new Date(), "hh:MM:ss");
        if (this.isHide) {
          return;
        }
        setTimeout(() => this.setClockTimeNow(), 1000);
      },
      getTodayClock() {
        console.log(this.userType);
        if (this.userType == 3) {
          getTeacherTodayClock({
            clockRole: 3,
            studyTimeId: this.stId,
            clockUserId: this.userId,
            findTime: this.formatDate,
            subjectId: this.info.sId,
          }).then((res) => {
            // this.todayList = res.data;
            if (res.data && res.data[0]) {
              this.upInfo = res.data[0];
            }
            if (res.data && res.data[1]) {
              this.downInfo = res.data[1];
            }
          });
        } else if (this.userType == 4) {
          getTodayClock({
            clockRole: 4,
            studyTimeId:this.stId,
            clockUserId: this.userId,
            findTime: this.formatDate,
            subjectId: this.info.sId,
          }).then((res) => {
            console.log("res", res);
            // this.todayList = res.data;

            if (res.data && res.data[0]) {
              if (res.data[0].upDown == 1) {
                this.upInfo = res.data[0];
              } else {
                this.downInfo = res.data[0];
              }
            }
            if (res.data && res.data[1]) {
              if (res.data[1].upDown == 1) {
                this.upInfo = res.data[1];
              } else {
                this.downInfo = res.data[1];
              }
            }
          });
        }
      },
      confirmClockStatus(e) {
        this.query.clockStatus = e.value[0].value;
        this.clockStatusText = e.value[0].label;
        this.statusShow = false;
        this.refresh()
      },
      confirmClockTime(e) {
        console.log(e)
        let startTime = e[0] + ' 00:00:00';
        let endTime = e[e.length - 1] + ' 23:59:59';
        this.query['clockTime%5B0%5D'] = encodeURIComponent(startTime);
        this.query['clockTime%5B1%5D'] = encodeURIComponent(endTime);
        this.clockTimeText = startTime + ' - ' + endTime;
        this.showClockTime = false;
        this.refresh()
      },
      reset() {
        this.query = {
          clockStatus: '',
          'clockTime%5B0%5D': '',
          'clockTime%5B1%5D': '',
          pageNo: 1,
          pageSize: 10,
        }
        this.clockStatusText = '';
        this.clockTimeText = '';
        this.refresh()
      },
      refresh() {
        this.query.pageNo = 1;
        this.clockList = [];
        this.isLast = false;
        this.getList();
      },
      getList() {
        if (this.isLast) return;
        if (this.userType == 3) {
          getTeacherClockList(uni.$u.queryParams({
            ...this.query,
            clockUserId: this.userId,
            studyTimeId: this.info.stId,
          })).then((res) => {
            this.clockList = this.clockList.concat(res.data.list);
            this.query.pageNo++;
            if (this.clockList.length == res.data.total) {
              this.isLast = true;
            }
          });
        } else if (this.userType == 4) {
          getStudentClockList(uni.$u.queryParams({
            ...this.query,
            clockUserId: this.userId,
            studyTimeId: this.info.stId,
          })).then((res) => {
            console.log("res", res);
            this.clockList = this.clockList.concat(res.data.list);
            this.query.pageNo++;
            if (this.clockList.length == res.data.total) {
              this.isLast = true;
            }
          });
        }
      },
      clockIn() {
        if (this.userType == 3) {
          uni.navigateTo({
            url: '/pages/user/ScanCode' + this.$u.queryParams(this.info),
          });
        } else if (this.userType == 4) {
          createClock({
            clockRemark: "",
            classesId: this.info.cId,
            clockRole: 4,
            clockType: 'hand',
            roomId: this.info.rId,
            subjectId: this.info.sId,
            weekId: this.info.wId,
            studyTimeId: this.info.stId,
            clockUserId: this.userId,
          }).then((res) => {
            if (res.code == 0) {
              this.$u.toast('打卡成功', 2000, () => {
                uni.navigateBack({
                  delta: 1
                })
              });
            } else {
              this.$u.toast(res.msg)
            }
          });
        }
      },
      btnClick(flag) {
        if (flag == 1) {
          this.btnType1 = "primary";
          this.btnType2 = "default";
          return;
        }
        this.btnType1 = "default";
        this.btnType2 = "primary";
      },
    },
  };
</script>

<style>
  page {
    background-color: #f8fafb;
  }
</style>
<style lang="scss" scoped>
  .main {
    widht: 100%;
    height: 100%;

    .collapse {
      padding: 30rpx;

      .status {
        border-radius: 10rpx 0px 0px 10rpx;

        &.normal {
          background: rgba(21, 109, 190, 0.08);
          color: #156dbe;
        }

        &.error {
          background: rgba(223, 69, 58, 0.08);
          color: #DF453A
        }
      }
    }



    .logInfo {
      margin: 30rpx;
      background-color: #fff;
      padding: 30rpx;

      text {
        color: #999999;
        width: 100%;
        // white-space: nowrap;
      }

      view {
        margin: 10px;
      }
    }

    .clock-btn {
      position: absolute;
      bottom: 5%;
      left: 50%;
      transform: translateX(-50%);
    }

    .click-btn {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      background: #182044;
      padding: 10px;
      // line-height: 60px;
      // text-align: center;
      color: #c4ad8c;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }

    .clock {


      .clock-item {
        width: 50%;
      }
    }
  }

  .btn-group {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 44px;
    padding: 10px 10px;
    background-color: #fff;

    .btn {
      width: 45%;
    }
  }

  /deep/ .u-reset-button::after {
    border: 1px solid #ccc;
  }

  /deep/ .u-button {
    // width: 40%;
  }

  .flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  uni-button {
    margin: 0;
  }
</style>
